package com.kyang.musiconline.utils;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import com.kyang.musiconline.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

/**
 * @author kyang
 */
@Component
public class JwtUtil {
    /**
     * 签名加密算法
     */
    private final static SecureDigestAlgorithm<SecretKey, SecretKey> ALGORITHM = Jwts.SIG.HS256;
    /**
     * signature签名
     */
    private final static String SIGNATURE = "qetuowryipadgjlsfhkzcbmxvnmbcznvxljgdakhfspiyrwouteq";
    /**
     * jwt失效时间(秒)
     */
    private final static int DESTROY_TIME = 60 * 60 * 8;

    public static String getToken(User musicUser) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("userId", musicUser.getId());
        JwtBuilder jwtBuilder = Jwts.builder()
                //唯一id
                .id(UUID.randomUUID().toString())
                .subject("MusicUser")
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + 1000 * DESTROY_TIME))
                //签名算法及秘钥
                .signWith(Keys.hmacShaKeyFor(SIGNATURE.getBytes()), ALGORITHM)
                .claims(map);
        return jwtBuilder.compact();
    }

    public static Jws<Claims> parseJWT(String token) {
        //密钥实例
        SecretKey key = Keys.hmacShaKeyFor(SIGNATURE.getBytes());
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token);
    }

    public static String getCurrentUserId() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Authorization");
            if (StrUtil.isNotBlank(token)) {
                Jws<Claims> claimsJws = parseJWT(token);
                return claimsJws.getPayload().get("userId").toString();
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
